package activities;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation.AnimationListener;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.intellifit.R;

import java.util.ArrayList;

import helper.Exercise;
import helper.ExercisesEnum;
import helper.Settings;
import helper.SharedPreferencesHelper;

public class RepetitionsActivitySitUps extends RepetitionsActivity implements
		OnClickListener, SensorEventListener, OnGestureListener,
		AnimationListener {

	private static final float NOISE = (float) 2.0;
	static final float lowerBound = 0.0f;
	static final float upperBound = 4.0f;

	public enum State {
		FROM_TOP_DOWN, FROM_BUTTOM_UP
	}

	private static boolean repStarted;;

	private Spinner spinner;
	private String[] viewSelection;

	private boolean increaseReps = true;

	private ArrayList<Float[]> accelMeasure = new ArrayList<Float[]>();
	private long repStartedTime;

	private int position = -1; // -1 unter 0, +1 über null
	int i = 0;
	boolean zweitesMal = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		thislistener = this;
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.view_repetions_include);

		RelativeLayout rl = (RelativeLayout) findViewById(R.id.overlay);
		rl.setBackgroundResource(R.drawable.bg_sit_ups_tap_to);

		this.currentExercise = new Exercise(3, "Sit ups", "Body Weigth");
		this.exerciseType = ExercisesEnum.SIT_UPS;
		sManager = (SensorManager) getSystemService(SENSOR_SERVICE);

		super.initLayoutComponents();
		registerListeners();
		gDetector = new GestureDetector(this, this);

		// initialize sharedPreferences before overlays are shown
		spHelper = new SharedPreferencesHelper(this);

		if (spHelper.mustShowExerciseInformation(this.exerciseType)) {
			showExerciseInfo();
		}

	}

	@Override
	public void reInit() {
		super.reInit();
		sManager.registerListener(this,
				sManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION),
				SensorManager.SENSOR_DELAY_UI);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		registerListeners();
	}

	public void handleAccelereometerEvent(SensorEvent event) {
		i++;
		float accelX = event.values[0];
		float accelY = event.values[1];
		float accelRootXY = (float) Math
				.sqrt(accelY * accelY + accelX * accelX);
		Log.i("ACCEL VALS", "" + accelRootXY);

		// if acceleration on x and y-axis is too high --> ignore
		if (accelRootXY >= 1) {
			return;
		}

		if (event.values[2] > 3 && i > 18 && position == -1) {
			++reps;
			repetitions++;
			updateCurrRepsView(reps);
			i = 0;
			position = 1;
		}

		if (event.values[2] <= 0) {
			position = -1;
		}
		// oben tal-berg, unten berg-tal
	}

	public void handleAccelereometerEvent2(SensorEvent event) {

		float x = event.values[0];
		float y = event.values[1];
		float z = event.values[2];

		// Length of acceleration for each axis
		float length = (float) Math.sqrt(z * z);
		float lengthY = (float) Math.sqrt(y * y);

		if (length >= 2.0 && length <= 7.5
				&& RepetitionsActivitySitUps.repStarted == false) {
			RepetitionsActivitySitUps.repStarted = true;
			Log.i("ACCEL VALS", "Len(Z): " + length + " Len(Y): " + lengthY);

		} else if (length >= 0 && length <= 1
				&& RepetitionsActivitySitUps.repStarted == true) {

			RepetitionsActivitySitUps.repStarted = false;
			Log.i("ACCEL VALS", "Len(Z): " + length + " Len(Y): " + lengthY);
			if (lengthY <= NOISE) {

				if (increaseReps)
					updateCurrRepsView(repetitions++);
				increaseReps = !increaseReps;

			}

			this.accelMeasure.clear();

		}
	}

	public void registerListeners() {

		sManager.registerListener(this,
				sManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION),
				SensorManager.SENSOR_DELAY_UI);
		findViewById(R.id.overlay).setOnClickListener(this);
		overlayStopExercise.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (started) {
					sManager.unregisterListener(thislistener);
					Settings.getInstance().lastExerciseDone = currentExercise;
					endTimeNS = System.nanoTime();
					updateDB();
					if (repetitions > 0) {
						Toast.makeText(
								getBaseContext(),
								"Congratulations! You've just completed "
										+ repetitions + " repetitions.",
								Toast.LENGTH_LONG).show();
					}
					repetitions = 0;
					createStatisticOverlay(false);

				}
			}
		});
	}

	@Override
	protected void onPause() {
		super.onPause();
		started = false;
		this.sManager.unregisterListener(this);
		if (!db_uptoDate)
			updateDB();
	}

	@Override
	public void onClick(View v) {

		// set the backgrounds for the running exercise
		overlayCountdown.setBackgroundResource(R.drawable.bg_situp);
		overlayStopExercise.setBackgroundResource(R.drawable.bg_situp);
		startCountDown();
		started = true;
	}

	@Override
	public void onSensorChanged(SensorEvent event) {

		if (started) {
			switch (event.sensor.getType()) {
			case Sensor.TYPE_LINEAR_ACCELERATION:
				handleAccelereometerEvent(event);
			}
		}

	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
	}
}
